<template>
  <div>
    <div>
      <button class="audio-btn audio-html-btn">
        audio tag
      </button>
       <audio class="audio" :src="src" preload="auto" ></audio>
    </div>
    <div>
      <audio id="audioV" :src="src" preload="auto"></audio>
      <button class="audio-btn" style="background: #f00;" @click.stop="playAudioVue">vue audio tag</button>
      <button
        class="audio-btn"
        style="background: #333;"
        @click.stop="playWebAudioVue"
      >vue play webAudio</button>
    </div>
    <button class="audio-btn audio-btn-html" style="background: #000;">
      <span style="color:#fff">play webAudio</span>
    </button>
    <button @click="getSound()">开始</button>
  </div>
</template>

<script>
import mp3  from "../assets/tet.mp3"
export default {
  name: "HelloWorld",
  data() {
    return {
      src:mp3,
      context: null,
      buffer: null
    };
  },
  props: {
    msg: String
  },
  methods: {
    getSound() {
      this.$nextTick(() => {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        this.context = new AudioContext();
        let that = this;
        const request = new XMLHttpRequest();
        request.open("GET", mp3, true);
        request.responseType = "arraybuffer";
        //下面就是对音频文件的异步解析
        request.onload = function() {
          that.context.decodeAudioData(request.response, function(buffer) {
            that.buffer = buffer;
          });
        };
        request.send();
      });
    },
    playAudioVue() {
      let audioEl = document.getElementById("audioV");
      audioEl
        .play()
        .then(() => {})
        .catch(e => {
          console.log(e);
          audioEl.play();
        });
    },
    playWebAudioVue() {
      var source = this.context.createBufferSource();
      source.buffer = this.buffer; //  告诉音频源 播放哪一段音频
      source.connect(this.context.destination); // 连接到输出源
      source.start(0); //开始播放
      console.log("我被播放了", this.context, source);
    }
  }
};
</script>
<style>
html,
body {
  background: #aaa;
  padding: 0;
  border: 0;
  margin: 0;
  height: 100%;
}

.audio-btn {
  display: block;
  width: 100px;
  height: 100px;
  background: #999;
}
</style>
